#pragma once

#include <sys/select.h>
#include <unistd.h>
#include <memory>
#include <algorithm>
#include <string>

#include "Socket.hpp"
#include "Log.hpp"

class SelectServer
{
private:
    template<class T>
    const T& max(const T& a, const T& b)
    {
        return a>b?a:b;
    }
public:
    SelectServer(uint16_t port) : _port(port), _listensock(std::make_unique<TcpSocket>())
    {
        _listensock->BuildListenSocket(_port);
    }

    void Init()
    {
        for (int i = 0; i < gnum; i++)
        {
            _fd_array[i] = gdefaultfd;
        }
        _fd_array[0]=_listensock->Sockfd();
    }

    void Accepter()
    {
        InetAddr addr;
        int fd = _listensock->Accept(&addr);
        if (fd > 0)
        {
            LOG(INFO, "Get a new link: %s\n", addr.AddrStr().c_str());
            int flag = 1;
            for (int i = 0; i < gnum; i++)
            {
                if (_fd_array[i] == gdefaultfd)
                {
                    _fd_array[i] = fd;
                    flag = 0;
                    break;
                }
            }
            if (flag)
            {
                LOG(WARNING, "FD_SET FULL\n");
            }
        }
        else
            LOG(ERROR, "accept error\n");
    }

    void HandlerIO(int i)
    {
        char buffer[1024];
        int n = ::recv(_fd_array[i], buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
            std::string echo_str = "<html><h1>hello bite</h1></html>";
            std::string echo("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nContent-Length: " +
                             std::to_string(echo_str.size()) + "\r\n\r\n" + echo_str);
            ::send(_fd_array[i], echo.c_str(), echo.size(), 0);
        }
        else if (n == 0)
        {
            LOG(INFO, "fd: %d -> quit\n", _fd_array[i]);
            _fd_array[i] = gdefaultfd;
            ::close(_fd_array[i]);
        }
        else
        {
            LOG(INFO, "fd: %d -> recv error\n", _fd_array[i]);
            _fd_array[i] = gdefaultfd;
            ::close(_fd_array[i]);
        }
    }

    void HandlerEvent(fd_set &rfds)
    {
        for (int i = 0; i < gnum; i++)
        {
            if (_fd_array[i] == gdefaultfd)
                continue;
            if (!FD_ISSET(_fd_array[i], &rfds))
                continue;
            if (_listensock->Sockfd() == _fd_array[i])
            {
                Accepter();
            }
            else
            {
                HandlerIO(i);
            }
        }
    }

    void Loop()
    {
        while (1)
        {
            fd_set rfds;
            FD_ZERO(&rfds);
            int max_fd = 0;
            for (int i = 0; i < gnum; i++)
            {
                if (_fd_array[i] != gdefaultfd)
                {
                    FD_SET(_fd_array[i], &rfds);
                    max_fd = max(_fd_array[i], max_fd);
                }
            }
            timeval timeout = {3, 0};
            int n = select(max_fd + 1, &rfds, nullptr, nullptr, &timeout);
            switch (n)
            {
            case 0:
                std::cout << "time out" << std::endl;
                break;
            case -1:
                std::cout << "select error" << std::endl;
                break;
            default:
                std::cout << "haved event ready, n:" << n << std::endl;
                HandlerEvent(rfds);
                break;
            }
        }
    }

    ~SelectServer() {}

private:
    const static int gnum = sizeof(fd_set) * 8 - 3;
    const static int gdefaultfd = -1;
    std::unique_ptr<TcpSocket> _listensock;
    uint16_t _port;
    int _fd_array[gnum];
};
